# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(optparse)
library(magrittr)
library(ggpubr)
library(tidyverse)
library(RJSONIO)
library(FSA)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--config", default = "calculate_config.json", type = "character", help = "config file"),
  make_option("--index", default = "", type = "character", help = "index")
)
opt <- parse_args(OptionParser(option_list = option_list))

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

options(digits = 3)

originalData<-read_tsv(str_c(opt$index, ".result.txt")) %>%
  rename(Metabolite = 1)

sampleIds<-originalData %>%
  select(-"Metabolite") %>%
  colnames()

sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  filter(SampleID %in% sampleIds) %>%
  select(c("SampleID", "ClassNote"))

groups <- sampleInfo %>%
  .$ClassNote %>%
  unique()

groups

allData <-originalData  %>%
  rowwise() %>%
  do({
    result <- as_tibble(.)
    metaboliteTb <- result %>%
      select(c("Metabolite"))
    for (group in groups) {
      sampleIds <- sampleInfo %>%
        filter(ClassNote == group) %>%
        .$SampleID
      groupData <- result[sampleIds] %>%
        unlist()
      result[, paste0(group, ".Mean")] <- mean(groupData)
      result[, paste0(group, ".SD")] <- sd(groupData)
      result[, paste0(group, ".Median")] <- median(groupData)
      iqr11 <- quantile(groupData, 0.25)
      iqr12 <- quantile(groupData, 0.75)
      iqr1 <- paste0("[", iqr11, ",", iqr12, "]")
      result[, paste0(group, ".IQR")] <- iqr1
      result[, paste0(group, ".Min")] <- min(groupData)
      result[, paste0(group, ".Max")] <- max(groupData)
    }
    result
  }) %>%
  select(-sampleIds)

allData

parent <- paste0("./")
allFileName <- paste0(parent, "/Statistics.csv")
write.csv(allData, allFileName, row.names = FALSE)












